<template>
  <div style="padding: 6px">
    <el-card v-show="showSearch" style="margin-bottom: 6px">
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px" style="margin-bottom: -20px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="queryParams.groupName" placeholder="请输入分组名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item v-if="isAdmin" label="我的分组" style="margin: 0 20px">
          <el-switch v-model="myGroup" @change="myGroupChange"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button v-hasPermi="['iot:group:add']" type="primary" plain icon="el-icon-plus" size="mini"
            @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="padding-bottom: 100px">
      <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
        <el-table-column label="分组名称" align="left" prop="groupName" width="300" />
        <el-table-column label="区域名称" align="center" prop="areaName" width="200">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.district_selection" :value="scope.row.areaName" />
          </template>
        </el-table-column>
        <el-table-column label="分组排序" align="center" prop="groupOrder" width="100" />
        <el-table-column label="负责人" align="left" prop="createTime" width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.leaderName }} {{ scope.row.leaderTel }}</div>
            <!--            <div></div>-->
          </template>
        </el-table-column>
        <el-table-column label="经纬度" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.latitude }},{{ scope.row.longitude }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isAdmin" label="所属用户" align="center" prop="userName" width="100" />
        <el-table-column label="备注" align="left" header-align="center" prop="remark" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="320">
          <template slot-scope="scope">
            <el-button v-hasPermi="['iot:device:list']" size="small" type="warning" style="padding: 5px"
              icon="el-icon-search" @click="handleViewDevice(scope.row.groupId)">查看设备</el-button>
            <el-button v-hasPermi="['iot:group:add']" size="small" type="success" style="padding: 5px"
              icon="el-icon-edit" @click="selectDevice(scope.row)">添加设备</el-button>
            <el-button v-hasPermi="['iot:group:query']" size="small" type="primary" style="padding: 5px"
              icon="el-icon-view" @click="handleUpdate(scope.row)">查看</el-button>
            <el-button v-hasPermi="['iot:group:remove']" size="small" type="danger" style="padding: 5px"
              icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />

      <!-- 分组设备列表 -->
      <deviceList ref="groupDeviceList" :group="group"></deviceList>

      <!-- 添加或修改设备分组对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="分组名称" prop="groupName">
            <el-input v-model="form.groupName" placeholder="请输入分组名称" />
          </el-form-item>
          <el-form-item label="区域名称" prop="areaName">
            <el-select style="width: 100%;" v-model="form.areaName" placeholder="请选择区域名称" clearable size="small">
              <el-option v-for="dict in dict.type.district_selection" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="分组排序" prop="groupOrder">
            <el-input v-model="form.groupOrder" type="number" placeholder="请输入分组排序" />
          </el-form-item>
          <el-form-item label="负责人" prop="leaderName">
            <el-input v-model="form.leaderName" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="联系方式" prop="leaderTel">
            <el-input v-model="form.leaderTel" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="站点经度" prop="latitude">
            <div style="background-color: rgba(192, 196, 204,0.3);display: flex;justify-content: space-between;">
              <div v-if="form.latitude" style="padding: 0 5px">{{ form.latitude }},{{ form.longitude }}</div>
              <div v-else style="padding: 0 5px;color: rgba(192, 196, 204,1)">请选择经纬度</div>
              <el-button type="primary" @click="mapFun">选择经纬度</el-button>
            </div>
          </el-form-item>
          <!-- <el-form-item label="站点纬度" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入站点纬度" />
          </el-form-item> -->
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-show="form.groupId" v-hasPermi="['iot:group:edit']">修
            改</el-button>
          <el-button type="primary" @click="submitForm" v-hasPermi="['iot:group:add']" v-show="!form.groupId">新
            增</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="经纬度选择" :visible.sync="mapOpen" width="920px" append-to-body>
        <div style="display: flex;justify-content: space-between">
          <div style="width: 600px;height: 500px" id="container"></div>
          <div style="padding: 0 10px">
            选择的地址{{ getLng }}，{{ getLat }}
            <div>
              <div style="margin-top: 15px;">
                <el-input placeholder="请输入内容" v-model="inputSearch">
                  <template slot="append">
                    <el-button @click="vauleSearch" type="primary">搜索</el-button>
                  </template>
                </el-input>
              </div>
            </div>
            <div id="panel"></div>
            <div v-if="false" style="border: 1px solid #ebedf0;padding: 5px">
              <div class="panel_warp" @click="panelWarpFun(item)" :key="index" v-for="(item, index) in panellist">
                <div class="panel_warp_left">
                  <img style="width: 100%;height: 100%" :src="item.imgurl" alt="">
                </div>
                <div class="panel_warp_right">
                  <div>{{ item.name }}</div>
                  <div class="panel_warp_text">{{ item.cityname + 11 }}{{ item.adname }}{{ item.address }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitmap">确 定</el-button>
          <el-button @click="mapOpen = false">取 消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import deviceList from './device-list'
import { listGroup, getGroup, delGroup, addGroup, updateGroup } from '@/api/iot/group'
import { getUserId } from "@/utils/auth";

export default {
  name: 'Group',
  components: {
    deviceList,
  },
  dicts: ['district_selection'],
  data() {
    return {
      // 是否管理员
      isAdmin: false,
      // 我的分组
      myGroup: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备分组表格数据
      groupList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        userId: null,
      },
      // 设备分组
      group: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [
          {
            required: true,
            message: '分组名称不能为空',
            trigger: 'blur',
          },
        ],
        areaName: [
          {
            required: true,
            message: '区域名称不能为空',
            trigger: 'blur',
          },
        ],
        groupOrder: [
          {
            required: true,
            message: '分组排序不能为空,最大值为99',
            trigger: 'blur',
          },
        ],
        leaderName: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur',
          },
        ],
        leaderTel: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur',
          },
        ],
        latitude: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur',
          },
        ],
      },
      mapOpen: false,
      map: '',
      inputSearch: '',
      geocoder: '',
      marker: [],
      getLat: '',
      getLng: '',
      placeSearch: '',
      panellist: []
    }
  },
  created() {
    this.getList()
    this.init()
  },
  methods: {
    init() {
      if (this.$store.state.user.roles.indexOf('tenant') === -1 && this.$store.state.user.roles.indexOf('general') === -1) {
        this.isAdmin = true
      }
    },
    // 我的分组改变事件
    myGroupChange() {
      this.queryParams.userId = this.myGroup ? getUserId() : null
    },
    /** 查看设备按钮操作 */
    handleViewDevice(groupId) {
      this.$router.push({
        path: '/iot/device',
        query: {
          t: Date.now(),
          groupId: groupId,
        },
      })
    },
    /** 查询设备分组列表 */
    getList() {
      this.loading = true
      listGroup(this.queryParams).then((response) => {
        this.groupList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        groupId: null,
        groupName: null,
        groupOrder: null,
        userId: null,
        userName: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.groupId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加设备分组'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const groupId = row.groupId || this.ids
      getGroup(groupId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改设备分组'
      })
    },
    /** 选择设备 */
    selectDevice(row) {
      this.group = row
      // 刷新子组件
      this.$refs.groupDeviceList.openDeviceList = true
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.groupId != null) {
            updateGroup(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addGroup(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const groupIds = row.groupId || this.ids
      this.$modal
        .confirm('是否确认删除设备分组编号为"' + groupIds + '"的数据项？')
        .then(function () {
          return delGroup(groupIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'iot/group/export',
        {
          ...this.queryParams,
        },
        `group_${new Date().getTime()}.xlsx`
      )
    },
    setMapOption() {
      // initMap方法
      this.map = new AMap.Map('container', {
        center: [114.159568, 32.146324],
        zoom: 15
      });
      this.marker = new AMap.Marker(); //插件使用，点标记相关
      this.map.on('click', this.clickMapHandler); //点击地图方法

      // this.vauleSearch()
    },
    // 搜索
    vauleSearch() {
      this.map.remove(this.marker);
      let _this = this;
      AMap.plugin(["AMap.PlaceSearch"], function () {
        //构造地点查询类
        _this.placeSearch = new AMap.PlaceSearch({
          pageSize: 7, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: "4115", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          map: _this.map, // 展现结果的地图实例
          panel: "panel", // 结果列表将在此容器中进行展示。
          autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        _this.placeSearch.search(_this.inputSearch, function (status, result) {

          if (result.info == "OK") {
            let panell = result.poiList.pois
            console.log(panell)
            for (let item of panell) {

              if (item.photos && item.photos.length > 0) {
                item['imgurl'] = item.photos[0].url;
              } else {
                item['imgurl'] = ''
              }
            }
            _this.panellist = panell
          }
        });
      });
      this.placeSearch.on("markerClick", this.clickMarkerHandler)
      // this.placeSearch.on("panelClick", this.clickMarkerHandler)
    },
    panelWarpFun(item) {
      console.log(item, 545555);
      this.clickMapHandler({
        lnglat: item.location
      })
    },
    clickMarkerHandler(res) {

      let lng = res.data.location.lng;
      let lat = res.data.location.lat;
      this.getLat = lat
      this.getLng = lng

    },
    clickMapHandler(e) {
      console.log(e, 'eeee')
      let lng = e.lnglat.getLng();
      let lat = e.lnglat.getLat();
      this.marker.setPosition([lng, lat]);
      this.map.add(this.marker);
      console.log([lng, lat]);
      this.getLat = lat
      this.getLng = lng
    },
    submitmap() {
      this.mapOpen = false
      this.form.latitude = this.getLat
      this.form.longitude = this.getLng
    },
    mapFun() {
      this.mapOpen = true
      this.getLng = ''
      this.getLat = ''
      setTimeout(() => {
        this.setMapOption()
      }, 100)

    }
  },
}
</script>
<style scoped>
.bigMap {
  width: 100%;
  height: 100%;
}

#panel {
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  width: 280px;
}

.panel_warp {
  display: flex;
  height: 60px;
  border-bottom: 1px solid rgb(232, 232, 232);
  margin-top: 5px;
}

.panel_warp_left {
  width: 50px;
  height: 50px;
}

.panel_warp_right {
  padding: 5px;
  font-size: 14px;
  font-weight: 700;
}

.panel_warp_text {

  color: #999;
  width: 200px;
  height: 50px;
  overflow: hidden;
  /*内容超出后隐藏*/
  text-overflow: ellipsis;
  /*超出内容显示为省略号*/
  white-space: nowrap;
  /*文本不进行换行*/
}
</style>
